

const { createApp, ref, computed, onMounted } = Vue;

const app = createApp({
    setup() {
        /// ==================== 全局变量定义 ====================
        //. Token
        let token = localStorage.getItem('token') || null;
        //. Base URL
        const BASE_URL = baseUrl; //. 这里是从url.js引入的baseUrl
        //. 默认headers
        axios.defaults.headers.common['Authorization'] = token;

        /// ==================== 全部用户相关方法 ====================

        //. 用户数据
        const users = ref([]);

        //. 获取用户数据
        const fetchUsers = async () => {
            try {
                const response = await axios.get(`${BASE_URL}/user/getUserList`);

                if (response.data.code === 200) {
                    users.value = response.data.data || [];
                } else {
                    showToast('获取用户列表失败', 'error');
                }
            } catch (error) {
                console.error('获取用户列表失败:', error);
                showToast('获取用户列表失败，请稍后重试', 'error');
            }
        };

        //. 日期格式化函数
        const formatDate = (date = new Date(), fmt = "yyyy-MM-dd hh:mm:ss.SSS") => {
            function repair(num) {
                return (num < 10 ? ("0" + num) : num).toString();
            }
            let o = {
                "yyyy": repair(date.getFullYear()),
                "MM": repair(date.getMonth() + 1),
                "dd": repair(date.getDate()),
                "hh": repair(date.getHours()),
                "mm": repair(date.getMinutes()),
                "ss": repair(date.getSeconds()),
                "SSS": date.getMilliseconds(),
                "e": date.getDay()
            }
            fmt = fmt.replace(/yyyy|MM|dd|hh|mm|ss|SSS|e/g, function (v) {
                return o[v];
            });

            return fmt;
        };

        //.编辑用户信息
        const editUserInfo = async () => {
            try {
                const response = await axios.put(`${BASE_URL}/user/updateUser`, formData.value);

                if (response.data.code === 200) {
                    showToast('用户信息更新成功', 'success');
                    fetchUsers(); //. 刷新用户列表
                } else {
                    showToast('用户信息更新失败' + response.data.message, 'error');
                }

                closeModal(); //. 关闭模态框
            } catch (error) {
                console.error('更新用户信息失败:', error);
                showToast('更新用户信息失败，请稍后重试', 'error');
            }
        };

        //. 保存用户信息
        const saveUser = async () => {
            formData.value.permission = parseInt(formData.value.permission, 10); //. 确保权限是整数
            if (formData.value.username === '') {
                showToast('用户名不能为空', 'error');
                return;
            }
            editUserInfo(); //. 调用编辑用户信息函数
        };

        //. 删除用户
        const deleteUser = async (user) => {
            try {
                //. 确认删除操作
                if (!confirm(`确定要删除用户 "${user.username}" 吗？`)) {
                    return;
                }

                const response = await axios.delete(`${BASE_URL}/user/deleteUser?id=${user.id}`);

                if (response.data.code === 200) {
                    showToast('用户删除成功', 'success');
                    fetchUsers(); //. 刷新用户列表
                } else {
                    showToast('用户删除失败' + response.data.message, 'error');
                }
            } catch (error) {
                console.error('删除用户失败:', error);
                showToast('删除用户失败，请稍后重试', 'error');
            }
        };

        //. 是否是小屏幕设备
        const isMobile = ref(false);

        //. 核心检测逻辑
        const detect = () => {
            const ua = navigator.userAgent || navigator.vendor || window.opera;
            const hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
            const screenWidth = window.innerWidth || document.documentElement.clientWidth;

            //. 用户代理检测（覆盖主流移动设备）
            const uaPattern = /(android|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|harmony)/i;

            //. 组合判断条件
            isMobile.value = uaPattern.test(ua) && (hasTouch || screenWidth < 768);
        };

        //. 选择的权限
        //. 这里的权限值是根据实际需求设置的，0表示游客，1表示用户，2表示会员，3表示管理员，4表示超级管理员，5表示开发者
        const selectedPermission = ref(-1);

        //. 改变权限
        const changePermission = (permission) => {
            selectedPermission.value = permission.target.value;
        }

        /// ==================== 用户认证相关方法 ====================

        //. 默认用户信息
        const defaultUser = {
            id: 0,
            username: '游客',
            phone: '',
            permission: 0,
            recorddate: '',
            email: '',
            logintime: '',
            collection: ''
        };

        //. 当前用户信息
        const currentUser = ref(defaultUser);

        //. 检查登录状态
        const checkLoginStatus = async () => {
            try {
                //. 如果没有token，直接重定向
                if (!token) {
                    showToast('请先登录', 'error');
                    setTimeout(() => {
                        window.location.href = '../../index.html';
                    }, 1500);
                    return;
                }

                //. 获取用户信息
                const response = await axios.post(`${BASE_URL}/user/getUserByToken`);

                if (response.data.code === 200) {
                    //. 设置当前用户信息
                    currentUser.value = response.data.data;

                    //. 获取用户权限
                    const userPermission = currentUser.value.permission;

                    //. 判断权限 - 允许管理员(3)、超级管理员(4)和开发者(5)访问
                    if (userPermission === 3 || userPermission === 4 || userPermission === 5) {
                        //. 允许访问，获取数据
                        // await fetchSites();
                        return;
                    } else {
                        //. 其他权限，显示提示并重定向
                        showToast('您没有权限访问此页面', 'error');
                        setTimeout(() => {
                            window.location.href = '../../index.html';
                        }, 1500);
                    }
                } else {
                    //. 获取用户信息失败，重定向到首页
                    showToast('请先登录', 'error');
                    setTimeout(() => {
                        window.location.href = '../../index.html';
                    }, 1500);
                }
            } catch (error) {
                //. 发生错误，重定向到首页
                showToast('系统错误，请稍后重试', 'error');
                setTimeout(() => {
                    window.location.href = '../../index.html';
                }, 1500);
            }
        };

        //. 退出登录
        const logout = async () => {
            try {
                //. 清除本地存储的token
                localStorage.removeItem('token');

                //. 清除axios默认headers中的token
                delete axios.defaults.headers.common['Authorization'];

                //. 重置用户状态
                currentUser.value = defaultUser;

                //. 显示退出成功提示
                showToast('已成功退出登录', 'success');

                //. 延迟跳转到首页
                setTimeout(() => {
                    window.location.href = '../../index.html';
                }, 1500);
            } catch (error) {
                console.error('退出登录失败:', error);
                showToast('退出登录失败，请重试', 'error');
            }
        };

        /// ==================== 导航相关方法 ====================
        //. 返回首页
        const goBack = () => {
            window.location.href = '../../index.html';
        };

        /// ==================== 搜索相关方法 ====================

        //. 搜索相关变量
        const searchQuery = ref('');
        const isSearching = ref(false);

        //. 搜索用户
        const search = async () => {
            if (!searchQuery.value.trim()) {
                showToast('请输入搜索关键词', 'error');
                return;
            }

            isSearching.value = true;
            try {
                //. 判断输入是否为纯数字
                const isNumeric = /^\d+$/.test(searchQuery.value.trim());

                let response;
                if (isNumeric) {
                    //. 如果是纯数字，进行ID查询
                    response = await axios.get(`${BASE_URL}/user/getUserById?id=${searchQuery.value.trim()}`);
                    if (response.data.code === 200) {
                        //. 将单个结果转换为数组
                        users.value = response.data.data ? [response.data.data] : [];
                    } else {
                        users.value = [];
                        showToast('未找到该ID的用户', 'info');
                    }
                } else {
                    //. 如果不是纯数字，进行名称模糊查询
                    response = await axios.get(`${BASE_URL}/user/getUserByNameLike?username=${encodeURIComponent(searchQuery.value.trim())}`);
                    if (response.data.code === 200) {
                        users.value = response.data.data;
                        if (users.value.length === 0) {
                            showToast('未找到匹配的分类', 'info');
                        }
                    } else {
                        users.value = [];
                        showToast('搜索失败', 'error');
                    }
                }
            } catch (error) {
                console.error('搜索失败:', error);
                showToast('搜索失败，请稍后重试', 'error');
                users.value = [];
            } finally {
                isSearching.value = false;
            }
        };

        //. 重置搜索
        const resetSearch = async () => {
            searchQuery.value = ''; //. 重置搜索关键词
            isSearching.value = false; //. 重置搜索状态
            selectedPermission.value = -1; //. 重置权限选择


            //. 重新获取用户数据
            await fetchUsers();
        };

        //. 过滤网站数据 - 只显示权限小于等于当前用户权限的数据，并根据分类过滤
        const filteredUsers = computed(() => {
            //. 首先根据权限过滤
            let filtered = users.value.filter(site =>
                currentUser.value && currentUser.value.permission >= site.permission &&
                (site.permission == selectedPermission.value || selectedPermission.value == -1)
            );

            return filtered;
        });

        /// ==================== 权限管理相关方法 ====================
        //. 获取权限等级文本
        const getPermissionText = (permission) => {
            const permissionMap = {
                0: '游客',
                1: '用户',
                2: '会员',
                3: '管理员',
                4: '超级管理员',
                5: '开发者'
            };
            return permissionMap[permission] || '未知';
        };

        //. 获取权限等级样式类
        const getPermissionClass = (permission) => {
            const classMap = {
                0: 'visitor',
                1: 'user',
                2: 'member',
                3: 'admin',
                4: 'super-admin',
                5: 'developer'
            };
            return classMap[permission] || 'visitor';
        };

        /// ==================== 模态框相关方法 ====================

        //. 编辑用户
        const editUser = (user) => {
            formData.value = user;
            showModal.value = true;
        };

        //. 关闭模态框
        const closeModal = () => {
            resetModalState();
        };

        //. 模态框相关变量
        const showModal = ref(false);
        const formData = ref({
            id: '',
            username: '',
        });

        //. 重置模态框状态的方法
        const resetModalState = () => {
            //. 清空表单数据
            formData.value = {
                id: 0,
                username: '',
                phone: '',
                permission: 0,
                recorddate: 0,
                email: '',
                logintime: 0,
                collection: ''
            };
            //. 收藏夹数据清空
            favorites.value = {
                user: formData.value,
                data: []
            };
            //. 关闭模态框
            showCollectModal.value = false;
            showModal.value = false;
        };

        const showCollectModal = ref(false);
        const favorites = ref({
            user: {},
            data: []
        });
        const showCollect = async (user) => {
            try {
                const response = await axios.get(`${BASE_URL}/Fav/getFavData?collection=${user.collection}`);
                if (response.data.code === 200) {
                    if (response.data.data.length === 0) {
                        showToast('没有收藏数据', 'info');
                        return;
                    }

                    //. 设置收藏数据
                    favorites.value.user = user;
                    favorites.value.data = response.data.data;
                    showCollectModal.value = true;
                } else {
                    favorites.value = [];
                    showToast('获取收藏数据失败', 'error');
                }
            } catch (error) {
                console.error('获取收藏数据失败:', error);
                showToast('获取收藏数据失败，请稍后重试', 'error');
                favorites.value = [];
            }
        }

        /// ==================== Toast 提示相关方法 ====================
        //. Toast 状态
        const toast = ref({
            show: false,
            message: '',
            type: 'info'
        });

        //. 存储定时器ID
        let toastTimer = null;

        //. 存储所有活动的弹窗
        const activeToasts = new Set();

        //. 显示 Toast 的函数
        const showToast = (message, type = 'info') => {
            //. 创建新的 Toast 元素
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.classList.add(type);
            toast.textContent = message;

            //. 创建独立的容器
            const container = document.createElement('div');
            container.className = 'toast-container';
            container.appendChild(toast);
            document.body.appendChild(container);

            //. 添加到活动弹窗集合
            activeToasts.add(toast);

            //. 触发重排以启动动画
            toast.offsetHeight;

            //. 设置定时器
            const timer = setTimeout(() => {
                //. 添加消失动画
                toast.style.animation = 'slideUpOut 0.3s ease forwards';

                //. 动画结束后移除元素
                toast.addEventListener('animationend', () => {
                    container.remove();
                    activeToasts.delete(toast);
                });
            }, 3000);

            //. 存储定时器ID
            toast.dataset.timerId = timer;
        };

        /// ==================== 生命周期 ====================
        onMounted(() => {
            checkLoginStatus();//. 检查登录状态
            fetchUsers();//. 获取用户数据
            detect(); //. 检测设备类型
        });

        /// ==================== 返回值 ====================
        return {
            /// ==================== 数据管理相关方法 ====================
            filteredUsers,
            showCollect,
            editUser,
            saveUser,
            deleteUser,
            favorites,
            isMobile,
            selectedPermission,
            changePermission,
            /// ==================== 用户相关方法 ====================
            currentUser,
            logout,
            formatDate,
            /// ==================== 权限管理相关方法 ====================
            getPermissionText,
            getPermissionClass,

            /// ==================== 导航相关方法 ====================
            goBack,
            /// ==================== 搜索相关方法 ====================
            searchQuery,
            search,
            resetSearch,
            /// ==================== 模态框相关方法 ====================
            showModal,
            formData,
            closeModal,
            showCollectModal,
            /// ==================== Toast 提示相关方法 ====================
            toast,
            showToast

        }
    }
});

app.mount('#app');